package com.gt.common;

import cn.hutool.json.JSONObject;
import com.alibaba.fastjson.JSON;
import com.gt.platform.domain.ReportParam;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;

import java.net.URI;
import java.nio.charset.StandardCharsets;

@Slf4j
public class HttpUtils {
    private static String urlDecrypt = "http://10.188.185.55:8212/gtwebservice.asmx/Decrypt";
    private static String urlEncrypt = "http://10.188.185.55:8212/gtwebservice.asmx/Encrypt";
    private static String urlSend = "http://10.188.185.81:8001/ESBService.asmx/CallESB";
    private static String prik = "00FC9EC3D49650B9013ABA2DAAD3CB0C46A02C5F9B6931DFB8A5B0AA6F2D242FC0";
    private static String pubk = "048384A576A795F710BA3A941AD305E4A221476C3232611CE45F6DBE230B3B4AF286F5F81D41609317ECBDE928D575148D517FB5A220AAAC7FA7DAB09C4542BA2B";



    /**
     * 此处调用C#进行解密
     *
     * @param data
     * @return
     */
    public static String sendDecrypt(String data) {

        /**封装解密数据**/
        Decrypt decrypt = new Decrypt();
        decrypt.setCipherText(data);
        decrypt.setPrik(prik);
        String jsonString = JSON.toJSONString(decrypt);

        // 发送POST请求，获取微信登录凭证
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(urlDecrypt);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // 设置请求参数
            StringEntity requestEntity = new StringEntity(jsonString, StandardCharsets.UTF_8);
            httpPost.setEntity(requestEntity);
            // 发送请求，获取响应
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity,StandardCharsets.UTF_8);
                JSONObject jsonObject = new JSONObject(responseBody);
                String result = jsonObject.get("d").toString();
                return result;
            } else {
                log.error("解密远程调用失败！");
                return null;
            }
        } catch (Exception e) {
            log.error("解密异常！");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 此处调用C#进行加密
     *
     * @param data
     * @return
     */
    public static String sendEncrypt(String data) {
        /**封装加密数据**/
        Encrypt encrypt = new Encrypt();
        encrypt.setPlainText(data);
        encrypt.setPubk(pubk);
        String jsonString = JSON.toJSONString(encrypt);
        // 发送POST请求，获取微信登录凭证
        try (CloseableHttpClient client = HttpClients.createDefault()) {
            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(urlEncrypt);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // 设置请求参数
            StringEntity requestEntity = new StringEntity(jsonString, StandardCharsets.UTF_8);
            httpPost.setEntity(requestEntity);
            // 发送请求，获取响应
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity);
                JSONObject jsonObject = new JSONObject(responseBody);
                String result = jsonObject.get("d").toString();
                return result;
            } else {
                log.error("加密远程调用失败！");
                return null;
            }
        } catch (Exception e) {
            log.error("加密异常！");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 调用平台接口
     * @param data
     * @return
     */
    public static String sendData(String data) {

        try (CloseableHttpClient client = HttpClients.custom().setDefaultRequestConfig(RequestConfig.custom()
                .setConnectTimeout(5000)//连接超时时间
                .setSocketTimeout(10000)//数据读取超时时间
                .build()).build()) {
            URIBuilder uriBuilder = new URIBuilder(urlSend);
            uriBuilder.addParameter("xmlMessage", data);
            URI uri = uriBuilder.build();
            // 创建HttpGet请求
            HttpGet httpGet = new HttpGet(uri);

            HttpResponse response = client.execute(httpGet);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity);
                //log.info("响应数据：{}", responseBody);
                String string = XmlParse.parse(responseBody, "string");
                return string;
            } else {
                HttpEntity errorEntity = response.getEntity();
                if (errorEntity != null) {
                    String errorBody = EntityUtils.toString(errorEntity);
                    log.error("远程调用平台失败【1】！错误响应体：{}", errorBody);
                }
                return null;
            }
        } catch (Exception e) {
            log.error("远程调用平台失败【2】！");
            e.printStackTrace();
            return null;
        }
    }

    /**
     * 调用平台接口
     * @param data
     * @return
     */
    public static String sendDataPost(String data) {
        ReportParam reportParam = new ReportParam();
        reportParam.setXmlMessage(data);
        String jsonString = JSON.toJSONString(reportParam);
        // 发送POST请求，获取微信登录凭证
        try (CloseableHttpClient client = HttpClients.createDefault()) {

            // 创建HttpPost请求
            HttpPost httpPost = new HttpPost(urlSend);
            // 设置请求头
            httpPost.setHeader("Content-Type", "application/json;charset=UTF-8");
            // 设置请求参数
            StringEntity requestEntity = new StringEntity(jsonString, StandardCharsets.UTF_8);
            httpPost.setEntity(requestEntity);
            // 发送请求，获取响应
            HttpResponse response = client.execute(httpPost);
            StatusLine statusLine = response.getStatusLine();
            int statusCode = statusLine.getStatusCode();
            if (statusCode == 200) {
                HttpEntity entity = response.getEntity();
                String responseBody = EntityUtils.toString(entity);
                log.info("响应数据：{}", responseBody);
                JSONObject jsonObject = new JSONObject(responseBody);
                String result = jsonObject.get("d").toString();
                return result;
            } else {
                HttpEntity errorEntity = response.getEntity();
                if (errorEntity != null) {
                    String errorBody = EntityUtils.toString(errorEntity);
                    log.error("远程调用平台失败【1】！错误响应体：{}", errorBody);
                }
                return null;
            }
        } catch (Exception e) {
            log.error("远程调用平台失败【2】！");
            e.printStackTrace();
            return null;
        }
    }

}
